import pygetwindow as gw
import mss
import mss.tools
import cv2
import numpy as np
import time
import socket
import threading
import struct


def capture_game_window(window_title):
    try:
        # 查找窗口
        windows = gw.getWindowsWithTitle(window_title)
        if not windows:
            raise Exception(f"未找到标题为: {window_title} 的窗口")
        window = windows[0]
        # 不激活窗口，保持后台状态
        print(f"找到窗口: {window.title}")
        
        # 创建TCP服务器，监听9000端口
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.bind(('0.0.0.0', 9000))
        server_socket.listen(1)
        print("服务器已启动，监听端口9000...")
        
        # 设置mss捕获
        
            
        try:
            while True:  # 循环接受客户端连接
                client_socket, addr = server_socket.accept()
                print(f"客户端 {addr} 已连接")
                
                def handle_client(client_socket):
                    try:
                        while True:
                            start_time = time.time()

                            
                            
                            
                            #window.activate()
                            
                            left, top = window.topleft
                            width, height = window.size
                            # 验证窗口尺寸有效性
                            if width <= 0 or height <= 0:
                                raise ValueError(f"无效的窗口尺寸: {width}x{height}")

                            # 使用mss捕获窗口内容
                            with mss.mss() as sct:
                                  monitor = {'left': left, 'top': top, 'width': width, 'height': height}
                                  img = sct.grab(monitor)
                                  frame = np.array(img)
                                  frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
                            # 控制帧率
                            
                            
                            # 编码并发送帧到客户端
                            result, img_encoded = cv2.imencode('.jpg', frame)
                            if result:
                                data = img_encoded.tobytes()
                                # 添加4字节图像大小（大端字节序）
                                size_bytes = struct.pack('!I', len(data))
                                client_socket.sendall(size_bytes + data)
                                
                                # 显示捕获的帧
                                #cv2.imshow("Game Window Capture", frame)
                                
                                # 计算并打印FPS
                                try:
                                    fps = 1 / (time.time() - start_time)
                                except ZeroDivisionError:
                                    fps = 60
                                print(f"FPS: {fps:.2f}")
                                
                                # 按'q'键退出
                                if cv2.waitKey(1) & 0xFF == ord('q'):
                                    return
                    except BrokenPipeError:
                        print(f"客户端 {addr} 已断开连接")
                    finally:
                        client_socket.close()
                
                client_thread = threading.Thread(target=handle_client, args=(client_socket,))
                client_thread.start()
        except KeyboardInterrupt:
            print("服务器正在关闭...")
        finally:
            server_socket.close()
            cv2.destroyAllWindows()
            print("服务器已关闭")
            
    except Exception as e:
        print(f"发生错误: {e}")

if __name__ == "__main__":
    # 替换为你的窗口标题
    GAME_WINDOW_TITLE = r"w01"
    capture_game_window(GAME_WINDOW_TITLE)